package listen;

import ffmpeg.FFmpeg;
import ffmpeg.ProcessMap;
import file.FileOperating;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class Listener extends Thread{

    private FFmpeg fFmpeg;

    public Listener(FFmpeg fFmpeg) {
        this.fFmpeg = fFmpeg;
    }

    @Override
    public void run() {
        listen();
    }

    private void listen() {
        Process process = fFmpeg.getProcess();
        while (true) {
            if (!process.isAlive()) {
                ProcessMap.processManagerHashMap.remove(fFmpeg.getId());
                try {
                    synchronized (Listener.class) {
                        String filePath = "/tmp/ffmpeg-push/pids.txt";
                        String pid = fFmpeg.getPid();
                        List<String> pids = FileOperating.readFile(filePath);
                        if (pids == null) {
                            return;
                        }
                        pids.remove(pid);
                        new File(filePath).delete();
                        pids.forEach(p -> {
                            try {
                                FileOperating.writeFile(true, filePath, p);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
